import com.google.gson.Gson;
import mysql.DBTool;
import pojo.Book;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Optional;

/**
 * @author DASK
 * @date 2020/4/2 14:48
 * @description //TODO 处理图书管理操作请求
 */
public class BookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] path = req.getRequestURL().toString().split("/");
        resp.setContentType("application/json; charset=utf-8");// 指定返回的格式为JSON格式
        resp.setCharacterEncoding("UTF-8");
        PrintWriter writer = resp.getWriter();
        Gson gson = new Gson();
        switch (path[path.length - 1]) {
            case "addBook":
                Book book = streamToObj(req);
                Optional.ofNullable(book).ifPresent(DBTool::addBook);
                returnOK(writer);
                break;
            case "updateBook":
                Book book1 = streamToObj(req);
                Optional.ofNullable(book1).ifPresent(DBTool::updateBook);
                returnOK(writer);
                break;
            case "delBook":
                int id = Integer.valueOf(req.getParameter("id"));
                DBTool.delBook(id);
                returnOK(writer);
                break;
            case "queryAll":
                writer.write(gson.toJson(DBTool.listBook()));
                break;
        }
        writer.flush();
        writer.close();
    }

    //将json字符串反序列化为POJO对象
    private Book streamToObj(HttpServletRequest req) throws IOException {
        try (
                InputStream stream = req.getInputStream();
                InputStreamReader is = new InputStreamReader(stream, "utf-8");
                BufferedReader reader = new BufferedReader(is);
        ) {
            StringBuffer strb = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                strb = strb.append(line);
            }
            Gson gson = new Gson();
            System.out.println(strb.toString());
            Book book = gson.fromJson(strb.toString(), Book.class);
            return book;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void returnOK(PrintWriter writer) {
        writer.write("{\"status\":\"true\"}");
    }
}
